package cn.jd.pet.service.impl;

import cn.jd.basic.config.BussinessException;
import cn.jd.basic.domain.Point;
import cn.jd.basic.util.*;
import cn.jd.order.domain.OrderPetAcquisition;
import cn.jd.order.domain.OrderProduct;
import cn.jd.order.mapper.OrderPetAcquisitionMapper;
import cn.jd.order.mapper.OrderProductMapper;
import cn.jd.org.domain.Employee;
import cn.jd.org.domain.Shop;
import cn.jd.org.mapper.ShopMapper;
import cn.jd.pet.domain.FromSingleLog;
import cn.jd.pet.domain.SearchMasterMsg;
import cn.jd.pet.domain.SearchMasterMsgAuditLog;
import cn.jd.pet.dto.AcceptDto;
import cn.jd.pet.mapper.FromSingleLogMapper;
import cn.jd.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.jd.pet.mapper.SearchMasterMsgMapper;
import cn.jd.pet.query.SearchMasterMsgQuery;
import cn.jd.pet.service.ISearchMasterMsgService;
import cn.jd.basic.service.impl.BasicServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2022-11-01
 */
@Service
public class SearchMasterMsgServiceImpl extends BasicServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {
    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;
    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private FromSingleLogMapper fromSingleLogMapper;
    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;
    @Autowired
    private OrderProductMapper orderProductMapper;
    @Override
    public AjaxResult publish(SearchMasterMsg searchMasterMsg) {
        //保存数据到数据库
        searchMasterMsgMapper.save(searchMasterMsg);
        // 验证数据是否为null
        parameterIsNullCheck(searchMasterMsg);
        // 百度AI审核
        baiduAi(searchMasterMsg);
        // 保存失败日志

        // 调用百度地图
        Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
        //查询出所有是商店
        List<Shop> shops = shopMapper.findAll();
        Shop shop = DistanceUtil.getNearestShop(point, shops);
        // 绑定商铺数据
        if(shop!=null){
            searchMasterMsg.setShopId(shop.getId());
        }
        // 修改状态
        searchMasterMsg.setState(1);
        searchMasterMsgMapper.update(searchMasterMsg);
        // 修改状态
        return AjaxResult.me().success();
    }

    @Override
    public PageList<SearchMasterMsg> toauditTohandlePollFinish(SearchMasterMsgQuery query) {
        Integer count =searchMasterMsgMapper.toauditTohandlePollFinishcount(query);
        List<SearchMasterMsg> departments = searchMasterMsgMapper.toauditTohandlePollFinish(query);
        PageList<SearchMasterMsg> list = new PageList<>(count, departments);
        return list ;

    }

    /**
     * 接单
     * @param
     * @param
     */
    @Override
    public void accept(AcceptDto dto, Employee employee) {
        // 查询数据是否存在
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(dto.getMsgId());
        if(searchMasterMsg==null){
            throw new BussinessException("该数据不存在");
        }
        // j解决线程安全问题
        synchronized (searchMasterMsg.getId()){
            if(employee==null){
                throw new BussinessException("该员工不存在");
            }
            if(searchMasterMsg.getState()==1&& employee.getShopId().equals(searchMasterMsg.getShopId())){
                // 修改数据状态
                searchMasterMsg.setState(2);
                // 修改参数
                searchMasterMsgMapper.update(searchMasterMsg);



                if(employee.getShopId()!=null){
                    // 生成收购订单
                    OrderPetAcquisition orderPetAcquisition = new OrderPetAcquisition();
                    orderPetAcquisition.setOrderSn(CodeGenerateUtils.generateOrderSn(employee.getId()));
                    orderPetAcquisition.setDigest(dto.getNote());
                    // 添加订单过期时间
                    orderPetAcquisition.setLastcomfirmtime(new Date(System.currentTimeMillis()+3*24*60*60*1000));
                    orderPetAcquisition.setState(3);
                    orderPetAcquisition.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
                    orderPetAcquisition.setUserId(employee.getId());
                    orderPetAcquisition.setShopId(employee.getShopId());
                    orderPetAcquisition.setAddress(searchMasterMsg.getAddress());
                    orderPetAcquisition.setEmpId(employee.getId());
                    orderPetAcquisition.setSearchMasterMsgId(searchMasterMsg.getId());
                    orderPetAcquisitionMapper.save(orderPetAcquisition);
                }

                    OrderProduct orderProduct = new OrderProduct();
                    orderProduct.setState(0);
                    orderProduct.setSearchMasterMsgId(searchMasterMsg.getId());
                    orderProduct.setDigest(searchMasterMsg.getName());
                    orderProduct.setPrice(new BigDecimal(searchMasterMsg.getPrice()));
                    orderProduct.setOrderSn(CodeGenerateUtils.generateOrderSn(employee.getId()));
                    orderProduct.setPaySn(CodeGenerateUtils.generateUnionPaySn());
                    orderProduct.setShopId(employee.getShopId());
                    orderProduct.setUserId(employee.getId());
                    orderProduct.setProductId(searchMasterMsg.getProductid());
                    orderProductMapper.save(orderProduct);






            }

        }






    }

    /**
     * 拒单
     * @param id
     * @param employee
     */
    @Override
    public void reject(Long id, Employee employee) {
       // 修改订单的状态
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.findById(id);
        //将shop的id置空
        searchMasterMsg.setShopId(null);
        // 修改表单
        searchMasterMsgMapper.update(searchMasterMsg);
        // 保存日志
        FromSingleLog singleLog = new FromSingleLog();
        singleLog.setEmpname(employee.getUsername());
        singleLog.setPetname(searchMasterMsg.getName());
        singleLog.setNote("商家拒绝接单");
        fromSingleLogMapper.save(singleLog);

    }

    /**
     * 参数为空校验
     * @param searchMasterMsg
     */
    private void parameterIsNullCheck(SearchMasterMsg searchMasterMsg) {
        if(StringUtils.isEmpty(searchMasterMsg.getName())||StringUtils.isEmpty(searchMasterMsg.getAddress())){
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("参数不能为空，请在个人中心修改！！！");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BussinessException("参数不能为空，请在个人中心修改！！！");

        }
    }

    /**
     * 百度Ai校验
     * @param searchMasterMsg
     */
    private void baiduAi(SearchMasterMsg searchMasterMsg) {
        StringBuilder builder = new StringBuilder();
        builder.append(searchMasterMsg.getName())
                .append(searchMasterMsg.getAddress())
                .append(searchMasterMsg.getCoatColor())
                .append(searchMasterMsg.getNote());

        if(!BaiduAuditUtils.TextCensor(builder.toString())){
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("你输入的数据存在违规行为请在个人中心修改");
            searchMasterMsgAuditLogMapper.save(log);
            throw new BussinessException("你输入的数据存在违规行为请在个人中心修改");
        }
    }
}
